package net.wicp.tams.common.jdbc.spring;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;

import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.StringUtil;
//未做测试
@Configuration
@ConditionalOnClass(name = { "org.mybatis.spring.SqlSessionFactoryBean" })
public class MybatisConfig {
	@Bean(name = "primarySqlSessionFactory")
	@Primary
	@ConditionalOnBean(name = "primaryDatasource")
	public SqlSessionFactory rdsSqlSessionFactory(
			@Qualifier("primaryDatasource") javax.sql.DataSource primaryDataSource) throws Exception {
		final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(primaryDataSource);
		if (StringUtil.isNotNull(Conf.get("common.spring.mybatis.mapperLocations"))) {
			sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
					.getResources(Conf.get("common.spring.mybatis.mapperLocations")));
		}
		if (StringUtil.isNotNull(Conf.get("common.spring.mybatis.configLocation"))) {
			sessionFactory.setConfigLocation(new PathMatchingResourcePatternResolver()
					.getResource(Conf.get("common.spring.mybatis.configLocation")));
		}
		return sessionFactory.getObject();
	}

	@Bean(name = "primarySqlSessionTemplate")
	@Primary
	@ConditionalOnBean(name = "primarySqlSessionFactory")
	public SqlSessionTemplate testSqlSessionTemplate(
			@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

	@Primary
	@Bean(name = "primaryJdbcTemplate")
	@ConditionalOnBean(name = "primaryDatasource")
	public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDatasource") DataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}
}
